package cn.interestingshop.servlet.client;

import cn.interestingshop.entity.BaseOrder;
import cn.interestingshop.entity.Cart;
import cn.interestingshop.entity.Goods;
import cn.interestingshop.entity.User;
import cn.interestingshop.service.BaseOrderService;
import cn.interestingshop.service.GoodsService;
import cn.interestingshop.service.impl.BaseOrderServiceImpl;
import cn.interestingshop.service.impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@WebServlet("/BaseOrderInsertServlet")
public class BaseOrderInsertServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //2.获取请求参数
        //接收收货地址
        String address=request.getParameter("address");
        User user = (User)request.getSession().getAttribute("loginUser");
        Cart cart = (Cart)request.getSession().getAttribute("cart");
        //3.调用service进行业务处理
        BaseOrderService baseOrderService=new BaseOrderServiceImpl();
        BaseOrder baseOrder=new BaseOrder();
        baseOrder.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        baseOrder.setUserId(user.getId());
        baseOrder.setAccount(user.getAccount());
        baseOrder.setCreateTime(new Date());
        baseOrder.setAmount(cart.getSum());
        baseOrder.setUserAddress(address);
        int i = baseOrderService.insert(baseOrder,cart);
        //4.分析返回结果
        if(i>0){
            //4.清空购物车
            request.getSession().removeAttribute("cart");

            request.setAttribute("baseOrder",baseOrder);
            request.getRequestDispatcher("BuyCar_Three.jsp").
                    forward(request,response);
        }else{
            response.getWriter().print("<script>alert('下单失败');history.go(-1)</script>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
